package com.vpclub.locale.resolver;


import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @author : leimingchao
 * @date Date : 2021年08月02日 21:41
 */
public class MyLocaleResolver implements LocaleResolver {


    /**
     * 解析返回locale
     * @param request
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale locale = null;
        String localeStr = request.getParameter("locale");
        //如果带了locale参数，就用参数指定的区域信息，如果没带就用请求头的
        if (!StringUtils.isEmpty(localeStr)) {
            String[] split = localeStr.split("_");
            locale = new Locale(split[0],split[1]);
        } else {
            locale = request.getLocale();
        }
        return locale;
    }

    /**
     * 修改locale
     * @param request
     * @param response
     * @param locale
     */
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException(
                "Cannot change HTTP accept header - use a different locale resolution strategy");
    }
}
